<?php

function connect(){
    $link=mysql_connect('localhost','root','root') or die('连接失败');

    mysql_query('set names utf8');

    mysql_select_db('shop1') or die('指定数据库打开失败');

  return $link;

}



function insert($table,$array){
    $keys=join(",",array_keys($array));//join();
    $vals="'".join("','",array_values($array))."'";

    $sql="insert into {$table}($keys) values ({$vals})";//mysql insert函数
    // echo $sql;
    //  die();
    mysql_query($sql);

    return mysql_insert_id();

}




function update($table,$array,$where=null){
    //update set ,
    $str='';
    foreach($array as $key=>$val){
// key='val'
        $str.=$key."='{$val}',";
    }
    $str=rtrim($str,',');
    $sql="update {$table} set {$str}".($where==null?null:" where ".$where);
    //echo $sql;die();
    $res=mysql_query($sql);

    if($res){
        return mysql_affected_rows();
    }else{
        return false;
    }
}





function delete($table,$where=null){
    $where=$where==null?null:" where ".$where;
    $sql="delete from {$table} {$where}";
    mysql_query($sql);
//echo $sql;
// die();

    return mysql_affected_rows();
}





function fetchone($sql){
    $res=mysql_query($sql);
    $row=mysql_fetch_array($res);

    return $row[0];
}


function getRow($sql){
    $res=mysql_query($sql);
    if($res){
        return mysql_fetch_assoc($res);
    }else{
        echo 'sql错误:'.$sql;
    }
}


function fetchall($sql,$res_type=MYSQL_ASSOC){
    $res=mysql_query($sql);
    $rows=array();
//echo $sql;die();
    while(@$row=mysql_fetch_array($res,$res_type)){
        $rows[]=$row;
    }
    return $rows;
}






function getresnum($sql){
    $res=mysql_query($sql);

    return mysql_num_rows($res);
}



function getInsertId(){
    return mysql_insert_id();
}

